package com.ywm.controller;

import com.alibaba.fastjson.JSON;
import com.ywm.entity.Blog;
import com.ywm.service.BlogSrevice;
import com.ywm.service.ElasticSearchService;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("es")
public class ElasticSearchController {
    @Autowired
    private RestHighLevelClient client;
    @Autowired
    private ElasticSearchService ElasticSearchService;

    //将数据库中的数据添加至ElasticSearch缓存中
    @GetMapping("getBlog")
    public String getBlogAndToElasticSearch() {
        if (ElasticSearchService.getBlogAndToElasticSearch()) {
            return "获取数据成功";
        } else {
            return "获取数据失败";
        }
    }

    //根据条件从ElasticSearch筛选数据
    @GetMapping("getBlog/{keyword}/{pageNo}/{pageSize}")
    public List<Map<String, Object>> getBlogFromElasticSearch(@PathVariable String keyword, @PathVariable int pageNo, @PathVariable int pageSize) throws Exception {
        List<Map<String, Object>> list = ElasticSearchService.getBlogFromElasticSearch(keyword, pageNo, pageSize);
        System.out.println("============================================================");
        System.out.println(keyword+"   "+pageNo+"   "+ pageSize);
        System.out.println(list);
        System.out.println("============================================================");
        return list;
    }
}
